package com.example.uiclassassignments.Activity;

import android.annotation.SuppressLint;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;

import com.example.uiclassassignments.R;

import java.lang.reflect.Method;

public class OptionsMenuActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_coptions_menu);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        finish();
    }

    private void setIconsVisible(Menu menu) {
        if (menu != null) {//判断menu是否为空
            try {
                @SuppressLint("PrivateApi")
                Method method = menu.getClass().getDeclaredMethod("setOptionalIconsVisible", Boolean.TYPE);//如果不为空,就反射拿到menu的setOptionalIconsVisible方法
                method.setAccessible(true); //暴力访问该方法
                method.invoke(menu, true);//调用该方法显示icon
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        setIconsVisible(menu);
        MenuInflater menuInflater = getMenuInflater();
        menuInflater.inflate(R.menu.context_menu,menu);

//        MenuItem menuItem =  menu.add(Menu.NONE, Menu.FIRST + 1, 1, "菜单一");
//        menuItem.setIcon(R.drawable.icon_favo_p);
//        menuItem = menu.add(Menu.NONE, Menu.FIRST + 2, 2, "菜单二");
//        menuItem.setIcon(R.drawable.icon_write_p);

        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        switch (id)
        {
            case  R.id.file_edit:
                Toast.makeText(this,"file_edit选中",Toast.LENGTH_LONG).show();
                break;
            case  R.id.file_font:
                Toast.makeText(this,"file_font",Toast.LENGTH_LONG).show();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    protected void onBtnOnClick(View view)
    {

    }
}
